const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { getBailianClient } = require('../utils/bailian-client-adapter');
const { getConfig } = require('../utils/config-manager');

// 获取百炼客户端
// 注意：每次请求都重新获取客户端，以确保使用最新的配置
const getClient = () => getBailianClient();

// Configure multer for file uploads
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, '../uploads');
    // Create uploads directory if it doesn't exist
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // Generate unique filename with original extension
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, 'image-' + uniqueSuffix + ext);
  }
});

// File filter to only allow image files
const fileFilter = (req, file, cb) => {
  if (file.mimetype.startsWith('image/')) {
    cb(null, true);
  } else {
    cb(new Error('Only image files are allowed!'), false);
  }
};

const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB limit
  }
});

const router = express.Router();

/**
 * @route POST /api/bailian/completion
 * @desc Generate text completion using Bailian API
 */
router.post('/completion', async (req, res, next) => {
  try {
    const { prompt, maxTokens, temperature } = req.body;

    if (!prompt) {
      return res.status(400).json({ error: 'Prompt is required' });
    }

    // 获取客户端并调用方法
    const client = getClient();
    const response = await client.generateCompletion(prompt, maxTokens, temperature);
    res.json(response);
  } catch (error) {
    next(error);
  }
});

/**
 * @route POST /api/bailian/chat
 * @desc Generate chat response using Bailian API
 */
router.post('/chat', async (req, res, next) => {
  try {
    const { messages, maxTokens, temperature } = req.body;
    //console.log(req.body);
    if (!messages || !Array.isArray(messages) || messages.length === 0) {
      return res.status(400).json({ error: 'Valid messages array is required' });
    }

    // 获取客户端并调用方法
    const client = getClient();
    const response = await client.generateChat(messages, maxTokens, temperature);
    res.json(response);
  } catch (error) {
    next(error);
  }
});

/**
 * @route GET /api/bailian/status
 * @desc Check Bailian API status
 */
router.get('/status', (req, res) => {
  try {
    // 获取客户端对象，确保使用最新的配置
    const client = getClient();

    // 获取配置
    const config = getConfig();

    res.json({
      status: 'OK',
      message: 'Bailian API integration is configured',
      endpoint: config.bailian_api_endpoint || process.env.BAILIAN_API_ENDPOINT,
      modelId: config.bailian_model_id || process.env.BAILIAN_MODEL_ID,
      clientType: config.use_openai_client ? 'OpenAI' : 'Original',
      useOfficialApi: config.use_official_api ? 'Yes' : 'No'
    });
  } catch (error) {
    console.error('Status check error:', error);
    res.status(500).json({
      status: 'Error',
      message: `Failed to check status: ${error.message}`
    });
  }
});

/**
 * @route POST /api/bailian/image-analysis
 * @desc Analyze image using Bailian API
 */
router.post('/image-analysis', upload.single('image'), async (req, res, next) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: 'Image file is required' });
    }

    const { prompt, maxTokens, temperature } = req.body;

    if (!prompt) {
      return res.status(400).json({ error: 'Prompt is required' });
    }

    // 获取客户�?    const client = getClient();

    // Convert image to base64
    const imageBase64 = await client.imageToBase64(req.file.path);

    // Delete the uploaded file after converting to base64
    fs.unlink(req.file.path, (err) => {
      if (err) console.error('Error deleting file:', err);
    });

    // Call the API
    const response = await client.analyzeImage(
      imageBase64,
      prompt,
      maxTokens ? parseInt(maxTokens) : undefined,
      temperature ? parseFloat(temperature) : undefined
    );

    res.json(response);
  } catch (error) {
    next(error);
  }
});




/**
 * @route POST /api/bailian/image-analysis-base64
 * @desc Analyze image using Bailian API with base64 encoded image data
 */
router.post('/image-analysis-base64', async (req, res, next) => {
  try {
    const { imageBase64, prompt, maxTokens, temperature } = req.body;

    if (!imageBase64) {
      return res.status(400).json({ error: 'Image base64 data is required' });
    }

    if (!prompt) {
      return res.status(400).json({ error: 'Prompt is required' });
    }

    // // ��� base64 ��ʽ�Ƿ���ȷ
    // if (!/^[A-Za-z0-9+/=]+$/.test(imageBase64)) {
    //   return res.status(400).json({ error: 'Invalid base64 format' });
    // }

    // ��ȡ�ͻ���
    const client = getClient();
    console.log('analyzeImage',prompt);
    // ���� API
    const response = await client.analyzeImage(
      imageBase64,
      prompt,
      maxTokens ? parseInt(maxTokens) : undefined,
      temperature ? parseFloat(temperature) : undefined
    );
    console.log('response',response);
    res.json(response);
  } catch (error) {
    next(error);
  }
});
module.exports = { bailianRouter: router };


// /**
//  * @route POST /api/bailian/image-analysis-base64
//  * @desc Analyze image using Bailian API with base64 encoded image data
//  */
// router.post('/image-analysis-base64', async (req, res, next) => {
//   try {
//     const { imageBase64, prompt, maxTokens, temperature } = req.body;

//     if (!imageBase64) {
//       return res.status(400).json({ error: 'Image base64 data is required' });
//     }

//     if (!prompt) {
//       return res.status(400).json({ error: 'Prompt is required' });
//     }

//     // ��� base64 ��ʽ�Ƿ���ȷ
//     if (!/^[A-Za-z0-9+/=]+$/.test(imageBase64)) {
//       return res.status(400).json({ error: 'Invalid base64 format' });
//     }

//     // ��ȡ�ͻ���
//     const client = getClient();

//     // ���� API
//     const response = await client.analyzeImage(
//       imageBase64,
//       prompt,
//       maxTokens ? parseInt(maxTokens) : undefined,
//       temperature ? parseFloat(temperature) : undefined
//     );

//     res.json(response);
//   } catch (error) {
//     next(error);
//   }
// });
